<template>
    <el-form :model="props.dialogForm" label-width="auto">
        <el-form-item label="募捐项目图片:">
            <el-upload 
                ref="upload"
                class="avatar-uploader" 
                :action="fileUrl" 
                :show-file-list="false"
                :on-success="handleAvatarSuccess" 
                :on-error="handleAvatarError" 
                :before-upload="beforeAvatarUpload"
                :limit="1"
            >
                <el-image v-if="props.dialogForm.fundraisingProjectsPhoto"
                    :src="imageUrl + props.dialogForm.fundraisingProjectsPhoto" style="width: 100px; height: 100px;" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-row>
            <el-col :span="12">
                <el-form-item label="募捐项目名称:">
                    <el-input v-model="props.dialogForm.fundraisingProjectsName" placeholder="请输入募捐项目名称" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="期望募捐金额:">
                    <el-input v-model="props.dialogForm.expectedFundraisingAmount" placeholder="请输入期望募捐金额" type="number" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item label="募捐项目简介:">
            <el-input v-model="props.dialogForm.fundraisingProjectsIntroduction" placeholder="请输入募捐项目简介" type="textarea"
                :autosize="{ minRows: 1, maxRows: 2 }" />
        </el-form-item>
        <el-row>
            <el-col :span="12" v-if="props.isAdmin">
                <el-form-item label="募捐项目所属机构:">
                    <el-select v-model="props.dialogForm.agencyId" placeholder="请选择募捐项目所属机构" clearable>
                        <el-option v-for="item in agencyOptions" :key="item.agencyId" :label="item.agencyName"
                            :value="item.agencyId" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="募捐项目类型:">
                    <el-select v-model="props.dialogForm.fundraisingProjectsType" placeholder="请选择募捐项目类型" clearable>
                        <el-option v-for="item in fundraisingTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="募捐项目截止时间:">
                    <el-date-picker v-model="props.dialogForm.fundraisingProjectsEndTime" type="date"
                        placeholder="请选择募捐项目截止时间" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item label="募捐项目介绍:">
            <div style="border: 1px solid #ccc;width: 100%;">
                <!-- 工具栏 -->
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                <!-- 编辑器 -->
                <Editor style="height: 300px; overflow-y: hidden" v-model="dialogForm.fundraisingProjectsContent" :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" @customPaste="customPaste" />
            </div>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { onMounted, ref, onBeforeUnmount, shallowRef } from 'vue';
import { fundraisingTypeOptions, handleAvatarError, beforeAvatarUpload } from './ts/common';
import { fileUrl, imageUrl } from '../../api/request';
import { adminApi, donatorApi } from '../../api/app';
import { UploadInstance, UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
// 富文本编辑器文档链接: https://www.wangeditor.com/v5/getting-started.html
// 引入富文本编辑器CSS
import '@wangeditor/editor/dist/css/style.css';
// 导入富文本编辑器的组件
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

interface IAgency {
    agencyId: string;
    agencyName: string;
}

// 接收父组件传值
const props = defineProps(["dialogForm", "isAdmin"]);
/** 机构选项 */
const agencyOptions = ref<IAgency[]>([]);
const upload = ref<UploadInstance>();
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const toolbarConfig = {};
const editorConfig = ref({ placeholder: '请输入内容...', MENU_CONF: {} });

onMounted(() => {
    adminApi.getAgencyIdAndName().then((res: any) => {
        if (res) {
            agencyOptions.value = res;
        }
    })
})

/** 上传头像成功 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (res: any) => {
    props.dialogForm.fundraisingProjectsPhoto = res;
    upload.value!.clearFiles(); // 清除已上传文件
};

// 自定义图片上传
editorConfig.value.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    const forms = new FormData();
    forms.append('file', file);
    const photo = imageUrl + await donatorApi.uploadAvatar(forms); // 上传图片到服务器
    // 这里的file为上传的图片对象,insertFn传入
    insertFn(photo, 'img');
  },
};

// 自定义视频上传
editorConfig.value.MENU_CONF['uploadVideo'] = {
  async customUpload(file, insertFn) {
    console.log('上传视频', file);
  },
};

// 富文本编辑器生成后触发
const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 监听富文本编辑器粘贴行为
const customPaste = (editor, event, callback) => {
  // 获取粘贴的纯文本
  const text = event.clipboardData.getData('text/plain');
  if (text) {
    editor.insertText(text);
    event.preventDefault();
    callback(false);
  }
};

// 获取富文本html内容
const getEditorHTML = () => {
  return editorRef.value.getHtml();
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

defineExpose({ getEditorHTML });
</script>

<style>
</style>